package com.kaibes.module.token.service;

import java.util.List;

import org.springframework.stereotype.Service;

import com.kaibes.module.token.core.TokenBuilder;
import com.kaibes.module.token.pojo.Token;
import com.kaibes.module.token.pojo.TokenType;
import com.kaibes.orm.core.core.Page;
import com.kaibes.orm.curd.QueryBuilder;
import com.kaibes.orm.curd.SelectBuilder;
import com.kaibes.web.api.ResponseServiceImpl;

@Service
public class TokenService extends ResponseServiceImpl<Token> {

    public Token getByUserIdAndType(Integer userId, TokenType type) {
        return get(QueryBuilder.newBuilder().eq("user_id", userId).eq("type", type).build());
    }

    public int removeByUserIdAndType(Integer userId, TokenType type) {
        return super.remove(QueryBuilder.newBuilder().eq("user_id", userId).eq("type", type.name()).build());
    }

    public int removeByUserId(List<?> userIds) {
        return super.remove(QueryBuilder.newBuilder().inList("user_id", userIds).build());
    }

    public Page<Token> pageByNicknameLike(Integer current, Integer size, String search) {
        QueryBuilder builder = QueryBuilder.newBuilder().inSelect("user_id",
                SelectBuilder.newBuilder().setTableName("user").addColumn("id")
                        .addQuery(QueryBuilder.newBuilder().like("nickname", search).build()).build());
        return page(current, size, builder.build());
    }
    
    public Token save(String aesKey, String aesIv, int minutes, Integer userId, TokenType type) {
        Token token = TokenBuilder.newBuilder().setAesIv(aesIv).setAesKey(aesKey).setMinutes(minutes).setUserId(userId).build(type);
        removeByUserIdAndType(token.getUserId(), type);
        save(token);
        return token;
    }

}
